package com.common.app.widget.mybanner;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Animatable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.request.RequestOptions;
import com.common.app.R;
import com.common.app.helper.UserHelper;
import com.common.app.widget.mybanner.transformer.OverlayTransformer;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.controller.ControllerListener;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.image.ImageInfo;

import java.util.List;

public abstract class BaseOverlayPageAdapter extends PagerAdapter {
    private Context context;
    private List<BannerBean> imgUrls;
    //    private WeakReference<Bitmap>[] bitmaps;
    protected RequestOptions mRequestOptions;

    private Bitmap qrCodeBitmap;
    private BannerBean curBean;

    public BaseOverlayPageAdapter(Context context, @NonNull RequestOptions imageOptions) {
        this.context = context;
        this.mRequestOptions = imageOptions;
    }

    /**
     * item布局
     *
     * @return
     */
    protected abstract View itemView();

    public void setImgUrlsAndBindViewPager(ViewPager vp, List<BannerBean> imgUrls) {
        setImgUrlsAndBindViewPager(vp, imgUrls, 3, null);
    }

    public void setImgUrlsAndBindViewPager(ViewPager vp, List<BannerBean> imgUrls, int layerAmount, Bitmap qrCodeBitmap) {
        setImgUrlsAndBindViewPager(vp, imgUrls, layerAmount, -1, -1, qrCodeBitmap);
    }

    /**
     * @param vp
     * @param imgUrls
     * @param layerAmount 显示层数
     */
    public void setImgUrlsAndBindViewPager(ViewPager vp, List<BannerBean> imgUrls, int layerAmount, float scaleOffset, float transOffset, Bitmap qrCodeBitmap) {
        this.imgUrls = imgUrls;
        this.qrCodeBitmap = qrCodeBitmap;
        if (imgUrls != null && imgUrls.size() > 0) {
//            bitmaps = new WeakReference[imgUrls.size()];
            vp.setOffscreenPageLimit(layerAmount);
            OverlayTransformer transformer = new OverlayTransformer(layerAmount, scaleOffset, transOffset);
            vp.setPageTransformer(true, transformer);
        }

        if (this.imgUrls != null && !imgUrls.isEmpty()) {
            curBean = this.imgUrls.get(0);
        }
    }

    @Override
    public int getCount() {
        if (null == imgUrls)
            return 0;
        if (imgUrls.size() <= 1)
            return imgUrls.size();
        return Integer.MAX_VALUE;
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
        return view == o;
    }

    protected ImageView findImageView(View rootView) {
        ImageView iv = rootView.findViewById(R.id.card_invite_friends_iv);
        if (null != iv)
            return iv;
        if (rootView instanceof ImageView) {
            return (ImageView) itemView();
        }
        throw new RuntimeException("you should set one of ImageViews id=card_iv or rootView=ImageView");
    }

    protected SimpleDraweeView findImageView2(View rootView) {
        SimpleDraweeView iv = rootView.findViewById(R.id.card_invite_friends_iv);
        if (null != iv)
            return iv;
        if (rootView instanceof SimpleDraweeView) {
            return (SimpleDraweeView) itemView();
        }
        throw new RuntimeException("you should set one of ImageViews id=card_iv or rootView=ImageView");
    }

    static class MyControllerListener implements ControllerListener<ImageInfo> {

        private SimpleDraweeView view;

        private boolean isMeasured;

        private int screenWidth;
        private int screenHeight;

        public MyControllerListener(SimpleDraweeView view, int screenWidth, int screenHeight) {
            this.view = view;
            this.screenWidth = screenWidth;
            this.screenHeight = screenHeight;
        }

        @Override
        public void onFailure(String arg0, Throwable arg1) {

        }

        @Override
        public void onFinalImageSet(String arg0, ImageInfo info, Animatable arg2) {
            measured(info);
        }

        @Override
        public void onIntermediateImageFailed(String arg0, Throwable arg1) {

        }

        @Override
        public void onIntermediateImageSet(String arg0, ImageInfo arg1) {

        }

        @Override
        public void onRelease(String arg0) {

        }

        @Override
        public void onSubmit(String arg0, Object arg1) {

        }

        private void measured(ImageInfo info) {
            if (isMeasured) {
                return;
            }
            isMeasured = true;

            // 获取图片真实宽高
            int width = info.getWidth();
            int height = info.getHeight();

            // 获取图片显示控件宽度,基于宽度适配图片
            int viewWidth = screenWidth;
            float viewRatio = viewWidth * 1.0f / width;
            view.setLayoutParams(new LinearLayout.LayoutParams(viewWidth, (int) (height * viewRatio)));
        }

    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        final int p = position % imgUrls.size();
        curBean = imgUrls.get(p);
        final String imgUrl = imgUrls.get(p).getImgUrl();
        final int imgDr = imgUrls.get(p).getObjectType();
        View view = itemView();
        if (null == view) {
            throw new RuntimeException("you should set a item layout");
        }
//        final ImageView iv = findImageView(view);
//        if (null == iv) {
//            throw new RuntimeException("you should set a item layout");
//        }
//        if (null != bitmaps && null != bitmaps[p] && null != bitmaps[p].get()) {
//            iv.setImageBitmap(bitmaps[p].get());
//        }
//        Glide.with(context).asBitmap().load(imgUrl).apply(mRequestOptions).into(new SimpleTarget<Bitmap>() {
//            @Override
//            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
//                bitmaps[p] = new WeakReference<Bitmap>(resource);
//                iv.setImageBitmap(resource);
//            }
//
//            @Override
//            public void onLoadStarted(@Nullable Drawable placeholder) {
//                super.onLoadStarted(placeholder);
//                iv.setImageDrawable(placeholder);
//            }
//
//            @Override
//            public void onLoadFailed(@Nullable Drawable errorDrawable) {
//                super.onLoadFailed(errorDrawable);
//                iv.setImageDrawable(errorDrawable);
//            }
//        });

//        final ImageView iv = findImageView(view);
//        iv.setScaleType(ImageView.ScaleType.FIT_XY);
//
//        Glide.with(context)
//                .asBitmap()
//                .load(imgUrl)
//                .dontAnimate()
//                .transform(new GlideTopRoundTransform(10))
//                .placeholder(R.drawable.ps_image_placeholder)
//                .into(iv);

        final SimpleDraweeView iv = findImageView2(view);
        if (null == iv) {
            throw new RuntimeException("you should set a item layout");
        }

        DraweeController controller = Fresco
                .newDraweeControllerBuilder()
                .setUri(imgUrl)
                .setControllerListener(
                        new MyControllerListener(iv,context.getResources().getDimensionPixelSize(R.dimen.dp_210),context.getResources().getDimensionPixelSize(R.dimen.dp_465)))
                .build();
        iv.setController(controller);

        if (qrCodeBitmap != null && UserHelper.INSTANCE.getUser() != null) {
            final TextView inviteCodeTv = view.findViewById(R.id.invite_code_tv);
            inviteCodeTv.setText(UserHelper.INSTANCE.getUser().getId());
            final ImageView qriv = view.findViewById(R.id.qr_code_img);
            qriv.setImageBitmap(qrCodeBitmap);
        }

        container.addView(view);
        return view;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }

    public BannerBean getCurBean() {
        return curBean;
    }
}
